//
//  FirstUserVerificationController.m
//  ERP
//
//  Created by goldeney on 15/5/7.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "FirstUserVerificationController.h"
#import "ScanCodeViewController.h"
#import "WebServicePlatformRequest.h"
#import "ExitLoginService.h"
#import "ConfigurationHelper.h"
#import "NSDictionary+DataFormat.h"
#import "AESCrypt.h"

@interface FirstUserVerificationController ()

@property (nonatomic, strong) IBOutlet UIButton *scanButton;
@property (nonatomic, strong) IBOutlet UIButton *inputButton;
@property (nonatomic, strong) IBOutlet UIButton *callButton;

@end

@implementation FirstUserVerificationController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle:@"企业简码设置"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //状态栏字体改变
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    self.scanButton.layer.cornerRadius = 22;
    self.scanButton.layer.masksToBounds = YES;
    
    self.inputButton.layer.cornerRadius = 22;
    self.inputButton.layer.masksToBounds = YES;
    
    self.callButton.layer.cornerRadius = 22;
    self.callButton.layer.masksToBounds = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark 地址是否可以连接

- (void)checkHttpURLIsAvailable:(NSString*)customerCode
{
    //判断是否有效连接地址
    customerCode = [customerCode stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if(!(customerCode && customerCode.length>0)) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"无效的企业简码，请重新扫描或输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
        return;
    }
    
    //连接网络检查
    [self checkNetworkConnectIsAvailable:customerCode];
}

- (void)checkNetworkConnectIsAvailable:(NSString*)customerCode
{
    //参数设置
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:[AESCrypt encrypt:customerCode] forKey:@"customerCode"];
    
    //尝试连接网络是否正常
    WebServicePlatformRequest *content = [[WebServicePlatformRequest alloc] initWithMethodName:@"Customer_Service" dataArray:model];
    [content setShowLoadingPrompt:self.navigationController labelText:@"正在验证"];
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if (result.resultArray && result.resultArray.count>0) {
            //连接成功，进行数据保存处理
            [self saveCustomerInfo:result.resultArray customerCode:customerCode];
        } else {
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"无效的企业简码，请您仔细核对后再试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alter show];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"系统错误，请重新尝试连接:%@",error);
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"系统繁忙，请稍后再试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSString *errorMessage = nil;
        if(error.code == 2) errorMessage = @"系统繁忙，请稍后再试";
        else if(error.code == 1) errorMessage = @"网络好像没有连接好，请检查网络是否连接正常";
        else errorMessage = [NSString stringWithFormat:@"未知错误:YZE0x000%ld",error.code];
        
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:errorMessage delegate:nil
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
    }];
}

- (void)saveCustomerInfo:(NSArray*)customerArray customerCode:(NSString*)customerCode
{
    NSDictionary *dictionary = [customerArray firstObject];
    NSString *service_link = [dictionary objectFormatStringForKey:@"service_link"];
    NSString *customer_name = [dictionary objectFormatStringForKey:@"customer_name"];
    NSInteger service_type = [dictionary objectFormatIntegerForKey:@"JoinpointType"];
    
    //简码验证
    if (!(service_link && service_link.length >0)) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"无效的企业简码，请重新扫描或输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
        return;
    }
    
    //连接成功，进行数据保存处理
    //service_type连接类型 0-Webserver 1-javaweb
    ConfigurationCodeing *model = [[ConfigurationCodeing alloc] init];
    model.IpAddress = service_link;
    model.organization = customer_name;
    model.briefCode = customerCode;
    model.serverType = @(service_type);
    
    BOOL isSuccess = [ConfigurationHelper saveConfigurationData:model];
    if(isSuccess) {
        [self showProgressHUDText:@"验证成功"];
        [self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
    } else {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"未知错误:YZSB0x00%ld" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
    }
}

- (void)delayMethod
{
    //关闭页面，进入登录
    [ExitLoginService exitAppUserLogin];
}

#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    ZXResult *result = backValue;
    [self checkHttpURLIsAvailable:result.text];
}

#pragma mark -
#pragma mark UIButton Event

//扫描二维码
- (IBAction)scanCodeingSelector:(id)sender
{
    ScanCodeViewController *viewController = [[ScanCodeViewController alloc] init];
    viewController.backResultDelagate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}

//手动输入
- (IBAction)manualInputSelector:(id)sender
{
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入企业简码" message:@"请输入我们为您提供的企业简码，若没有企业简码，请咨询相关负责人。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"验证",nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeURL];
    dialog.delegate = self;
    [dialog show];
}

//联系我们
- (IBAction)callPhoneSelector:(id)sender
{
    [self callAction:@"4008501527"];
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    if (buttonIndex == 1) {//设置按钮
        UITextField *textField = [alertView textFieldAtIndex:0];
        [self checkHttpURLIsAvailable:textField.text];
    }
}

#pragma mark - 拨打电话
- (void)callAction:(NSString*)phoneNumber
{
    if (!(phoneNumber && ![phoneNumber isEqualToString:@""])) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未找到联系电话" delegate:self
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    } else {
        phoneNumber = [NSString stringWithFormat:@"tel://%@",phoneNumber];
    }
    
    //拨打电话(合法拨打电话方式)
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:phoneNumber];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

@end
